package org.linlinjava.litemall.admin.wx.handler;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

import org.apache.commons.lang3.StringUtils;
import org.linlinjava.litemall.admin.wx.builder.TextBuilder;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author Binary Wang
 */
@Component
public class MsgHandler extends AbstractHandler {

  @Override
  public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                  Map<String, Object> context, WxMpService wxMpService,
                                  WxSessionManager sessionManager) {
/*
    WeixinService weixinService = (WeixinService) wxMpService;

    if (!wxMessage.getMsgType().equals(WxConsts.XmlMsgType.EVENT)) {
      //TODO 可以选择将消息保存到本地
    }*/
/*
    //当用户输入关键词如“你好”，“客服”等，并且有客服在线时，把消息转发给在线客服
    if (StringUtils.startsWithAny(wxMessage.getContent(), "你好", "客服")) {
      return WxMpXmlOutMessage
        .TRANSFER_CUSTOMER_SERVICE().fromUser(wxMessage.getToUser())
        .toUser(wxMessage.getFromUser()).build();
    }*/

	  String content = "请稍等，如超5分钟未回复，请点击福利群，进群会有专人解答。";
	  
	  //获取商家openid
    if (StringUtils.startsWithAny(wxMessage.getContent(), "商家", "openId")) {
    	try {
			WxMpUser userWxInfo = wxMpService.getUserService().userInfo(wxMessage.getFromUser());
			content = "您的openId："+ userWxInfo.getOpenId();
		} catch (WxErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
      }
    
    //TODO 组装回复消息
    //String content = "回复信息内容";
    //return new TextBuilder().build(content, wxMessage, weixinService);

	    //TODO 组装回复消息
	    //String content = wxMessage.getContent();
	    return new TextBuilder().build(content, wxMessage, wxMpService);
  }

}
